import util from '@/utils/utils.js'
import { GetopenidByCode , CheckUserByOpenid,AddWxappUser } from '@/utils/api.js'

let all = 0
function _request(url, resolve, reject, data = {}, method = 'GET') {
	if(!uni.getStorageSync('noLoading')){
		util.showLoading('正在加载')
	}
	uni.setStorageSync('noLoading',false)
	let url_a=url.split('api/')[1]
	if('GetopenidByCode CheckUserByOpenid AddWxappUser'.indexOf(url_a)==-1){
		
		all += 1
		let token = uni.getStorageSync('token')
		uni.request({
			url: url,
			method: method,
			data: {...data},
			header: { 'Authorization': token , 'froms':'wxapp' , 'uniacid':10},
			success: (res) => {
				// util.hideLoading()
				if (res.statusCode == 200 ) {
					if(res.data.status == -2){
						uni.setStorageSync('token','')
						getToken()
						reject()
					}else{
						resolve(res.data)
					}
				} else {
					util.showMessage( obj2string(res.data))
					reject()
				}
			},
			fail: (err) => {
				// util.hideLoading()
				util.showMessage( err.errMsg)
				reject()
			},
			complete:()=>{
				all -= 1
				if(all==0){
					setTimeout(()=>{
						if(all==0){
							util.hideLoading()
						}
					},200)
				}else{
					setTimeout(()=>{
						util.hideLoading()
					},2500)
				}
			}
		})
	}else{
		
		all += 1
		let token = uni.getStorageSync('token')
		uni.request({
		  url: url,
		  method: method,
		  data: {...data},
		  header: { 'Authorization': token , 'froms':'wxapp' , 'uniacid':10},
		  success: (res) => {
				util.hideLoading()
		    if (res.statusCode == 200 ) {
					resolve(res.data)
		    } else {
		      util.showMessage( obj2string(res.data))
		      reject()
		    }
		  },
		  fail: (err) => {
				util.hideLoading()
		    util.showMessage( err.errMsg)
		    reject()
		  },
			complete:()=>{
				all -= 1
				if(all==0){
					setTimeout(()=>{
						if(all==0){
							util.hideLoading()
						}
					},200)
				}else{
					setTimeout(()=>{
						util.hideLoading()
					},2500)
				}
			}
		})
	}
}

function request(url, data = {}, method = 'GET') {
  return new Promise((resolve, reject) => {
    _request(url, resolve, reject, data, method)
  })
}

function jump2login() {
  uni.setStorageSync('token','')
  uni.redirectTo({
    url: '/pages/login/login'
  })
}

function obj2string(obj) {
  return JSON.stringify(obj)
}

function getToken(){
	
// #ifdef APP-PLUS
		jump2login()
// #endif
	
	
// #ifdef MP
		uni.login({
			provider: 'weixin',
			success: function (res) {
				GetopenidByCode({code:res.code}).then(res=>{
					uni.setStorageSync('openid',res.data.openid)
					CheckUserByOpenid({openid:uni.getStorageSync('openid'),role_id:uni.getStorageSync('role_id')}).then(res=>{
						uni.setStorageSync('token',res.data.token)
						uni.setStorageSync('userinfo', JSON.stringify(res.data))
					})
				})
			}
		 })
// #endif
}

export {
  request
}